//
//  MYGChooseView.swift
//  MYGrow
//
//  Created by 林矗 on 2024/3/16.
//

import UIKit
protocol MYGChooseViewModelProtocol {
    func getUniqueValue() -> String
    func getTitle() -> String
    func getSubtitle() -> String
    func isExclusion() -> Bool
}

extension MYGChooseViewModelProtocol {
    func isExclusion() -> Bool {
        if getTitle() == "无" || getTitle() == "全部" {
            return true
        }
        return false
    }
}

extension String: MYGChooseViewModelProtocol {
    func getUniqueValue() -> String {
        return self
    }
    
    func getTitle() -> String {
        return self
    }
    
    func getSubtitle() -> String {
        return ""
    }
}

class MYGChooseView: UIView {
    // MARK: - Property
    private var models: [MYGChooseViewModelProtocol] = []
    var selectedModels: [MYGChooseViewModelProtocol] = []
    var selectedItemsChangedAction: (([MYGChooseViewModelProtocol]) -> ())?
    var isSingleChoose = false
    // MARK: - init
    override init(frame: CGRect) {
        super.init(frame: frame)
        configUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - UI
    private func configUI() {
        self.backgroundColor = .white
        self.addSubview(collectionView)
    }
    
    
    
    // MARK: - Public funcs
    func reload(with models: [MYGChooseViewModelProtocol]) {
        self.models = models
        collectionView.reloadData()
        let mod = models.count % 3
        let row = mod == 0 ? (models.count / 3) : (models.count / 3 + 1)
        let height = CGFloat(row) * 26.0 + CGFloat(row - 1) * 12.5 + 15
        collectionView.snp.remakeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.size.equalTo(CGSize(width: screenWidth, height: height))
            make.bottom.equalToSuperview().offset(-bottomSafeheight-10)
        }
    }
    
    // MARK: - lazy load
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        let totalSpacing = (25.0 * 2 + 35.0 * 2)
        layout.itemSize = CGSize(width: (screenWidth - totalSpacing) / 3.0 , height: 26)
        layout.minimumLineSpacing = 12.5
        layout.minimumInteritemSpacing = 35
        layout.sectionInset = UIEdgeInsets(top: 0, left: 25, bottom: 15, right: 25)
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(cellWithClass: MYGChooseViewCell.self)
        return collectionView
    }()
}

extension MYGChooseView: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        models.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withClass: MYGChooseViewCell.self, for: indexPath)
        cell.title = models[indexPath.row].getTitle()
        cell.myg_isSelected = selectedModels.contains(where: { value in
            return value.getUniqueValue() == models[indexPath.row].getUniqueValue()
        })
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if isSingleChoose {
            selectedModels = [models[indexPath.row]]
        } else {
            if selectedModels.contains(where: { value in
                return value.getUniqueValue() == models[indexPath.row].getUniqueValue()
            }) {
                selectedModels.removeAll { value in
                    return value.getUniqueValue() == models[indexPath.row].getUniqueValue()
                }
            } else {
                if selectedModels.contains(where: {$0.isExclusion()}) {
                    selectedModels.removeAll(where: {$0.isExclusion()})
                } else {
                    if models[indexPath.row].isExclusion() {
                        selectedModels.removeAll()
                    }
                }
                selectedModels.append(models[indexPath.row])
            }
        }
        collectionView.reloadData()
        selectedItemsChangedAction?(selectedModels)
    }
}

